package com.example.lemis.web.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.lemis.mapper.NewsMapper;
import com.example.lemis.model.domain.SensitiveWords;
import com.example.lemis.model.dto.PageDTO;
import com.example.lemis.model.vo.NewsVO;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.lemis.common.JsonResponse;
import com.example.lemis.service.INewsService;
import com.example.lemis.model.domain.News;

import java.io.IOException;


/**
 *
 *  前端控制器
 *
 *
 * @author lxp
 * @since 2025-06-24
 * @version v1.0
 */
@RestController
@RequestMapping("/api/news")
public class NewsController {

    private final Logger logger = LoggerFactory.getLogger( NewsController.class );

    @Autowired
    private INewsService newsService;

    @Autowired
    private SensitiveWordsController sensitiveWordsController;


    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse<News> getById(@PathVariable("id") Long id)throws Exception {
        News news = newsService.getById(id);
        return JsonResponse.success(news);
    }

    /**
     * 描述：添加新闻
     * @param news(url,creatorId,clazz)
     * @return
     * @throws Exception
     */
    @PostMapping("/add")
    public JsonResponse<?> news_add(@RequestBody News news) throws Exception {
        Document doc = null;
        try {
            doc = Jsoup.connect(news.getUrl()).get();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        news.setTitle(doc.title());
        Elements elements = doc.select("p");
        String content = elements.text();
        if (content.length() > 2048) {
            content = content.substring(0, 2048);
        }
        news.setContent(content);
        NewsVO newsVO = newsService.news_add(news);
        return JsonResponse.success(newsVO);
    }

    /**
     * 描述：新闻分类查询
     * @param title, PageDTO(pageNo, pageSize)
     * @return
     * @throws Exception
     */
    @GetMapping("/enquire")
    public JsonResponse<?> news_search(String title, String clazz, PageDTO pageDTO) throws Exception {
        Page<NewsVO> newsVO = newsService.news_search(title, clazz, pageDTO);
        return JsonResponse.success(newsVO);
    }
}

